<!DOCTYPE HTML>
<html>
<head>
<title>Le Mur</title>
<script type="text/javascript" src="gl-matrix-0.9.5.js"></script>

<!-- DEBUT MUR -------------------------------------------------------------->
<script id="murScript" type="text/javascript">
  //pour canvas2d
  var murCanvas;
  var murCanvasContext;
  var murDebug = false;
  var murViewPort = [];
  var murDonnees = [];
  var mvMatrix = mat4.create();  
  /*| 0  1  2  3 |          | sx 0  0  0 |
    | 4  5  6  7 |          | 0  sy 0  0 |
    | 8  9  10 11|   =>     | 0  0  sz 0 |
    | 12 13 14 15|          | tx ty tz 1 |  */
  mat4.identity(mvMatrix);
  
  //pour la souris
  var murMouseStateEnum = { idle : 0, pressed : 1, draggingWhitinBounds : 2,
    dragging : 3 };
  var murMouseState = murMouseStateEnum.idle;
  var murMousePos = []; //x,y
  var murMouseDelta = []; //x,y
  var murMouseDeltaAccum = []; //x,y
  
  //-----------------------------------------------------------------------------
  /**
  * Provides requestAnimationFrame in a cross browser way.
  */
  window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
         window.webkitRequestAnimationFrame ||
         window.mozRequestAnimationFrame ||
         window.oRequestAnimationFrame ||
         window.msRequestAnimationFrame ||
         function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
           window.setTimeout(callback, 1000/60);
         };
  })();
  //-----------------------------------------------------------------------------
  /* x et y représente la position gl où le rectangle sera positionné.
     w et h reprente la largeur et la hauteur.
     a représente le point d'ancrage ie:
     
         0------1-------2
         |              |
         3      4       5
         |              |
         6------7-------8  */
  function drawRectangle(x, y, w, h, a)
  {
    var offset = [0.0, 0.0];
    
    switch(a)
    {
    case 0: offset = [0.0, 0.0]; break;
    case 1: offset = [-w/2.0, 0.0]; break;
    case 2: offset = [-w, 0.0]; break;
    case 3: offset = [0.0, -h/2.0]; break;
    case 4: offset = [-w/2.0, -h/2.0]; break;
    case 5: offset = [-w, -h/2.0]; break;
    case 6: offset = [0.0, -h];break;
    case 7: offset = [-w/2.0, -h]; break;
    case 8: offset = [-w, -h]; break;
    default: break;
    }
    
    murCanvasContext.strokeRect(x + offset[0], y + offset[0], w, h);
  }
  //-----------------------------------------------------------------------------
  function drawScene()
  {
    window.requestAnimFrame(drawScene, murCanvas);
		
    var trans = [ mvMatrix[12], mvMatrix[13] ];
    var zoom = mvMatrix[0]; //le zoom est uniforme
    murViewPort[0] = -trans[0] / zoom;
    murViewPort[1] = -trans[1] / zoom;
    murViewPort[2] = murCanvas.width / zoom;
    murViewPort[3] = murCanvas.height / zoom;
    murCanvasContext.clearRect( murViewPort[0], murViewPort[1],
	      murViewPort[2],  murViewPort[3]);
    
    murCanvasContext.setTransform(mvMatrix[0],0,
    	0, mvMatrix[5],
    	mvMatrix[12], mvMatrix[13]);

    murCanvasContext.fillText("Bouette", 100, 100);
    for(i = 0; i < murDonnees.length / 2; ++i)
    {
      drawRectangle(murDonnees[i * 2], murDonnees[(i * 2) + 1],
        4, 4, 4);
    }
  }
  //-----------------------------------------------------------------------------
  function handleMouseDown(event)
  {
    murMouseState = murMouseStateEnum.pressed;
    murMousePos = getRelativeMouseCoordinate(event);
  }
  //-----------------------------------------------------------------------------
  function handleMouseUp(event)
  {  
  	//on envoit le click si on est pas en dragging  
    if(murMouseState != murMouseStateEnum.dragging)
    {
    	pos = screenToCanvas(murMousePos);
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET",
        "mur-ajoute.php?x="+pos[0]+"&y="+pos[1], true);
      xmlhttp.send();
    }
    
    murMouseState = murMouseStateEnum.idle;
    murMousePos = getRelativeMouseCoordinate(event);
    murMouseDelta = [0, 0];
    murMouseDeltaAccum = [0, 0];
  }
  //-----------------------------------------------------------------------------
  function handleMouseMove(event)
  {
		if( murMouseState == murMouseStateEnum.idle )
    	return;
      
    if( murMouseState == murMouseStateEnum.pressed)
    	murMouseState = murMouseStateEnum.draggingWhitinBounds;
      
    var mousePos = getRelativeMouseCoordinate(event);
    var canvasPos = screenToCanvas(mousePos);
    
    murMouseDelta = [mousePos[0] - murMousePos[0], 
      mousePos[1] - murMousePos[1] ];
    murMouseDeltaAccum = [ murMouseDeltaAccum[0] + murMouseDelta[0], 
      murMouseDeltaAccum[1] + murMouseDelta[1] ];
    murMousePos = mousePos;
    
		if(murMouseState == murMouseStateEnum.draggingWhitinBounds && 
      ( Math.abs(murMouseDeltaAccum[0]) >= 3 || Math.abs(murMouseDeltaAccum[1]) >= 3) )
      murMouseState = murMouseStateEnum.dragging;
    
    if(murMouseState == murMouseStateEnum.dragging)
    { 
    	//on convertit le delta ecran en delta canvas
      var canvasDeltax = murMouseDelta[0] / mvMatrix[0]; //on multiplie par le zoom;
      var canvasDeltay = murMouseDelta[1] / mvMatrix[0]; //on multiplie par le zoom;
    	mat4.translate( mvMatrix, [ canvasDeltax, canvasDeltay, 0.0 ] );
    }
    
    if(murDebug)
    {    	
    	var d = "mousePos: " + mousePos[0] + " " + mousePos[1] + "<br>";
      d += "canvasPos: " + canvasPos[0] + " " + canvasPos[1] + "<br>";
      d += "murMousePos: " + murMousePos[0] + " " + murMousePos[1] + "<br>";
      d += "murMouseDelta: " + murMouseDelta[0] + " " + murMouseDelta[1] + "<br>";
      d += "murMouseDeltaAccum: " + murMouseDeltaAccum[0] + " " + murMouseDeltaAccum[1] + "<br>";
      document.getElementById("debugView").innerHTML=d;
    }
  }
  //-----------------------------------------------------------------------------
  function getRelativeMouseCoordinate(event)
  {
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var x = 0;
    var y = 0;
    var currentElement = murCanvas;

    do{
        totalOffsetX += currentElement.offsetLeft;
        totalOffsetY += currentElement.offsetTop;
    }
    while(currentElement = currentElement.offsetParent)

    x = event.pageX - totalOffsetX;
    y = event.pageY - totalOffsetY;
    return [x, y];
  }
  //-----------------------------------------------------------------------------
  //prend un vec2 et retourne un vec2
  function screenToCanvas(screenPos)
  {
  	/*On transforme la coordonnée écran pour quelle soit en coordonnée
      monde.*/
    var inv = mat4.create();
    mat4.inverse( mvMatrix, inv );
    var r = mat4.multiplyVec3(inv, [ screenPos[0], screenPos[1], 0.0 ] );
    return [ r[0], r[1] ];
  }
</script>
<!-- FIN MUR SCRIPT ---------------------------------------------------------------->

<!-- DEBUT CONTENUR DU MUR ----------------------------------------------------->
<script type = "text/javascript">

	function handleKeyDown(event)
  {
  	document.getElementById("inputText").focus();
    if(event.keyCode == 13 ) //la touche retour
    {
    	var s = document.getElementById("inputText").value;
      
      if(s == "debug")
      {
    		murDebug = !murDebug;
  	    var d;
	      murDebug ? d = "block" : d = "none";
      	document.getElementById("murDonneesTd").style.display = d;
        document.getElementById("debugViewTd").style.display = d;
    	} 
      else if( s == "+")
      	mat4.scale(mvMatrix, [2, 2, 1]);
      else if( s == "-" )
      	mat4.scale(mvMatrix, [0.5, 0.5, 1]);

    	//on efface le contenu du champs
    	document.getElementById("inputText").value = "";
    }
  }
    
	function initializePage()
  {
    //initialisation du canvas 2d
    murCanvas = document.getElementById("canvas2d");
    murCanvasContext = murCanvas.getContext('2d');
    murCanvasContext.fillStyle = "#333333"; 	// This determines the text colour, it can take a hex value or rgba value (e.g. rgba(255,0,0,0.5))
		murCanvasContext.textAlign = "center";	// This determines the alignment of text, e.g. left, center, right
		murCanvasContext.textBaseline = "middle";	// This determines the baseline of the text, e.g. top, middle, bottom
		murCanvasContext.font = "22px helvetica";	// This determines the size of the text and the font family used    
    
    murViewPort = [0, 0, murCanvas.width, murCanvas.height];
    murCanvasContext.setTransform(1, 0, 0, 1, 0, 0);    
    
    //ajout des events handler du canvas
    murCanvas.addEventListener("mousedown", handleMouseDown, false);
    murCanvas.addEventListener("mouseup", handleMouseUp, false);
    murCanvas.addEventListener("mousemove", handleMouseMove, false);
    
    //ajout des event handler du document
    document.onkeydown = handleKeyDown;
    
    drawScene();
    
    setTimeout('quand_maj ()', 250);
  }
  function maj()
  {
    var lastUpdate = "";
    var tokens;
    var j = 0;
    xmlhttp = new XMLHttpRequest();
    
    xmlhttp.onreadystatechange=function()
    {
    	var r;
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        murDonnees = [];
      	r = xmlhttp.responseText;
        document.getElementById("dataView").innerHTML=r;
        //document.getElementById("dataView").innerHTML = window.responseXML;
        
        /*les données ont la forme suivante:
        <!DOCTYPE HTML>
        <html>
        <head>
        </head>


        <body>

          ,52,49,12,48,blablabla,
        </body>
        </html>"
        On élimine donc le token 0 et le dernier token qui sont les
        entetes HTML.
        */
        tokens = r.split(",");
        for(var i = 1; i < tokens.length-1; ++i, ++j)
        {
          murDonnees[j] = parseFloat(tokens[i]);
        }
        lastUpdate = tokens[i];
      }
    }
    xmlhttp.open("GET",
      "mur-maj.php?lastUpdate="+lastUpdate+"&t="+ Math.random(), true);
    xmlhttp.send();
  }
  function quand_maj ()
  {
    maj () ;
    setTimeout ("quand_maj ()", 1000) ;
  }
</script>
<!-- FIN CONTENUR DU MUR ------------------------------------------------------>
</head>

<body onLoad = "initializePage()">
<table>
  <tr>  	
  	<td valign="TOP"><canvas id="canvas2d" style="border:solid 1px #000000;" width="400" height="400">html canvas pas supporté!</canvas></td>
  </tr>
  <tr>
  	<td><input type="text" id="inputText" value="" /><td/>
  </tr>
  <tr>
  	<td id="debugViewTd" style="DISPLAY: none"><div id="debugView"><div/></td>
  </tr>
  <tr>
  	<td valign="TOP" id="murDonneesTd" style="DISPLAY: none"><div id="dataView">Les donnees vont ici...</div></td>
  </tr>
</table>
</body>
</html>